package sc;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.UIManager;

public final class Harlequin extends JFrame implements Runnable
{
	public static final String CLIENT_TITLE = "Harlequin";
	public static final String BASE_PATH = System.getProperty("user.home") + "/Harlequin";
	
	private static final long serialVersionUID = 1L;
	private static Harlequin instance;
	private static TopPanel toppanel;

	/**
	 * Constructs an instance of Harlequin
	 * 
	 * @throws IOException
	 * @throws SecurityException
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws SQLException
	 */
	public Harlequin()
	{
		// Define the window attributes
		setSize(260, 400);
		setTitle(CLIENT_TITLE);
		setIconImage(Images.getImage("/images/harlequin.png"));

		// Define what to do on window events
		addWindowListener(new WindowAdapter()
		{
			public void windowClosing(WindowEvent e)
			{
				Tray.showHideItem(false);
			}
		});

		Container content = this.getContentPane();
		content.setLayout(new BorderLayout());

		// Add the top bar
		toppanel = new TopPanel();
		content.add(toppanel, BorderLayout.NORTH);

		// Add the members scrolling panel
		Component members = PanelControl.getInstance();
		JScrollPane scroller = new JScrollPane(members);
		scroller.getVerticalScrollBar().setBlockIncrement(12);
		content.add(scroller, BorderLayout.CENTER);

		content.add(Log.getComponent(), BorderLayout.SOUTH);
	}

	public void run()
	{
		try
		{
			while (true)
			{
				PanelControl.update();
				Thread.sleep(Configuration.updateRate());
			}
		} catch (Exception e)
		{
			String indent = "";
			Log.error(e.getLocalizedMessage());
			for (StackTraceElement element : e.getStackTrace())
			{
				Log.error(indent + (indent.equals("") ? "" : "\\- ")
						+ element.getClassName() + "."
						+ element.getMethodName());
				indent += " ";
			}
		}
	}

	public static void main(String[] args)
	{
		// Use the native look and feel
		try
		{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e)
		{
		}

		(new File(Harlequin.BASE_PATH)).mkdirs();
		Configuration.initialise();
		Tray.initialise();
		instance = new Harlequin();
		new Thread(instance).start();
	}

	public static Harlequin getInstance()
	{
		return instance;
	}
}
